<template>
  <div class="profile-container">
    <div class="profile-card">
      <h2>个人资料</h2>
      <div class="avatar-box">
        <div class="avatar-container" @click="triggerFileInput">
          <img :src="getAvatarUrl()" width="80" class="avatar" @error="handleAvatarError" />
          <div class="avatar-overlay">
            <span>点击上传</span>
          </div>
        </div>
        <input 
          ref="fileInput" 
          type="file" 
          accept="image/*" 
          @change="handleFileUpload" 
          style="display: none;" 
        />
      </div>
      <div>
        <input v-model="user.bio" placeholder="个人简介" class="input" />
      </div>
      <div>
        <input v-model="user.email" placeholder="邮箱" class="input" />
      </div>
      <button @click="updateProfile" class="btn">保存</button>
    </div>
    <div class="my-articles-card">
      <h2>我的文章</h2>
      <ul class="my-article-list">
        <li v-for="a in myArticles" :key="a.id" class="my-article-item">{{ a.title }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import UserStorage from '@/utils/userStorage'

export default {
  data() {
    return {
      user: { id: null, avatar_url: '', bio: '', email: '' },
      myArticles: [],
      defaultAvatar: '',
      avatarLoadError: false,
      mockMyArticles: [
        { id: 1, title: '我的第一篇文章' },
        { id: 2, title: '我的第二篇文章' }
      ]
    }
  },
  methods: {
    getAvatarUrl() {
      // 如果头像加载出错，使用默认头像
      if (this.avatarLoadError) {
        return this.defaultAvatar
      }
      
      // 如果没有头像URL或URL为空，使用默认头像
      if (!this.user.avatar_url || this.user.avatar_url.trim() === '') {
        return this.defaultAvatar
      }
      
      // 如果已经是完整的URL地址，直接返回
      if (this.user.avatar_url.startsWith('http://') || this.user.avatar_url.startsWith('https://')) {
        return this.user.avatar_url
      }
      
      // 如果是相对路径，添加后端服务地址
      if (this.user.avatar_url.startsWith('/')) {
        return `http://localhost:8081${this.user.avatar_url}`
      }
      
      return this.user.avatar_url
    },
    
    handleAvatarError() {
      // 头像加载失败时，使用默认头像
      this.avatarLoadError = true
      console.warn('头像加载失败，使用默认头像')
    },
    
    async fetchProfile() {
      try {
        // 从localStorage获取用户信息
        const userInfo = UserStorage.getUserInfo()
        if (userInfo) {
          this.user = {
            id: userInfo.id,
            avatar_url: userInfo.avatarUrl || '',
            bio: userInfo.bio || '',
            email: userInfo.email || ''
          }
        } else {
          // 如果没有用户信息，跳转到登录页面
          this.$router.push('/login')
          return
        }
        
        // TODO: 获取用户文章列表
        // const response = await axios.get('/boke-user/articles')
        // this.myArticles = response.data
        
        // 模拟文章数据
        this.myArticles = this.mockMyArticles
      } catch (error) {
        console.error('获取用户资料失败:', error)
      }
    },
    async updateProfile() {
      try {
        // 组装要提交的数据
        const data = {
          id: this.user.id,
          email: this.user.email,
          bio: this.user.bio
        }
        // 调用后端接口
        await axios.put('/boke-user/update-profile', data)
        // 更新localStorage中的用户信息
        const userInfo = UserStorage.getUserInfo()
        if (userInfo) {
          userInfo.email = this.user.email
          userInfo.bio = this.user.bio
          UserStorage.saveUserInfo(userInfo)
        }
        alert('资料保存成功')
      } catch (error) {
        alert('保存失败: ' + (error.response?.data || error.message))
      }
    },
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    async handleFileUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件')
        return
      }
      
      // 检查文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        alert('文件大小不能超过5MB')
        return
      }
      
      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('userId', this.user.id)
        
        // 显示上传中状态
        this.$el.querySelector('.avatar-overlay span').textContent = '上传中...'
        
        const response = await axios.post('/boke-user/upload-avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (response.data.avatarUrl) {
          this.user.avatar_url = response.data.avatarUrl
          this.avatarLoadError = false // 重置错误状态
          
          // 更新localStorage中的用户信息
          UserStorage.updateAvatarUrl(response.data.avatarUrl)
          
          alert('头像上传成功')
        }
      } catch (error) {
        console.error('上传失败:', error)
        alert('头像上传失败: ' + (error.response?.data || error.message))
      } finally {
        // 恢复原始状态
        this.$el.querySelector('.avatar-overlay span').textContent = '点击上传'
        // 清空文件输入框
        this.$refs.fileInput.value = ''
      }
    }
  },
  mounted() {
    this.fetchProfile()
  }
}
</script>

<style scoped>
.profile-container {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}
.profile-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(66,185,131,0.08);
  padding: 32px 28px 24px 28px;
  min-width: 320px;
  flex: 1;
}
.avatar-box {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 18px;
}
.avatar-container {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: transform 0.2s;
}
.avatar-container:hover {
  transform: scale(1.05);
}
.avatar {
  border-radius: 50%;
  border: 2px solid #42b98333;
  display: block;
}
.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  border-radius: 50%;
}
.avatar-overlay span {
  color: white;
  font-size: 12px;
  font-weight: bold;
}
.avatar-container:hover .avatar-overlay {
  opacity: 1;
}
.input {
  width: 100%;
  margin-bottom: 18px;
  padding: 10px 14px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  font-size: 1rem;
  outline: none;
  transition: border 0.2s;
}
.input:focus {
  border: 1.5px solid #42b983;
}
.btn {
  width: 100%;
  background: #42b983;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 0;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  margin-bottom: 10px;
  transition: background 0.2s;
}
.btn:hover {
  background: #1890ff;
}
.my-articles-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(66,185,131,0.08);
  padding: 32px 28px 24px 28px;
  min-width: 320px;
  flex: 1;
}
.my-article-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.my-article-item {
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
  color: #1890ff;
  cursor: pointer;
  transition: color 0.2s;
}
.my-article-item:hover {
  color: #42b983;
}
</style> 